const http = require('../../utils/http.js')
const qiniuUploader = require("../../utils/qiniuUploader");
Page({
  data: {
    urls: [{
      url: "/images/add.png",
      id: 0
    }, ],
    addPicUrl: "/images/add.png", //点击添加图片按钮的图片
    picUrl: [],
    num: 1,
    address: '点击选择地址', //点击选择地址设置地址值
    addressDetails: '', //详细地址
    addressDetailsText: '',
    time: true, //点击选择时间设置时间值
    //作物类型选择
    cropTypeText: '点击选择类型',
    cropTypeArr: [],
    forMatCropTypeArr: [],
    cropTypeIndex: 0,
    //作业类型
    isShow: false,
    taskTypeText: '点击选择类型',
    taskTypeArr: [],
    // forMatTaskTypeArr: [],
    taskText: '点击选择类型',
    taskTypeIndex: 0,
    valueArr: [],
    //作业亩数
    areaDetails: '',
    // 农药类型
    pesText: '点击选择类型',
    pesArr: [],
    forMatPesArr: [],
    pesIndex: 0,
    //食宿
    boardText: '点击选择类型',
    boardArr: [],
    forMatBoardArr: [],
    boardIndex: 0,
    starTime: null,
    endTime: null,
    agreement: true, //用户协议是否显示
    isConfirm: true,
    uploadToken: null,
    //boolArr: [], //复选框是否选中的数组
    contactText: '',
    phoneText: '',
    //是否支付定金
    depositArr: ['是', '否'],
    depositText: '是否支付定金',
    depositIndex: 0,
    //定金金额选择框是否显示
    isDepositShow: false,
    //定金金额选择
    depositMoneyText: '点击选择金额',
    depositMoneyArr: [],
    forMatDepositMoneyArr: [],
    depositMoneyIndex: 0,
    //期望金额
    moneyDetails: '',
    isSuccess: false
  },
  onLoad: function(options) {
    //请求七牛云token
    http.qiniuToken().then(res => {
      this.setData({
        uploadToken: res
      })
    })

    wx.request({
      url: 'https://api.mokyun.com/pesticide/login',
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'content-type': 'application/json',
        'APPID': 32
      },
      success(res) {
        // console.log(res)
        if (!res.data.tel) {
          wx.redirectTo({
            url: '/pages/certification/certification'
          });
        } else {
          // wx.redirectTo({
          //   url: '/pages/index/index'
          // });
          // console.log(4151515)
        }
      }
    })
    //请求作物类型
    http.getData("crop").then(res => {
      // console.log(res)
      let forMatCropTypeArr = this.data.forMatCropTypeArr;
      res.forEach((v, index) => {
        forMatCropTypeArr.push(v.crop_name)
      })
      this.setData({
        cropTypeArr: res,
        forMatCropTypeArr: forMatCropTypeArr
      })
    }).catch(res => {
      console.log(res)
    })
    //请求作业类型
    http.getData("task").then(res => {
      // console.log(res)
      this.setData({
        taskTypeArr: res
      })
    }).catch(res => {
      console.log(res)
    })

    //请求农药信息
    http.getData("pesticide").then(res => {
      // console.log(res)
      let forMatPesArr = this.data.forMatPesArr;
      res.forEach((v, index) => {
        forMatPesArr.push(v.pesticide_name)
      })
      this.setData({
        pesArr: res,
        forMatPesArr: forMatPesArr
      })
    }).catch(res => {
      console.log(res)
    })
    //请求食宿信息
    http.getData("board").then(res => {
      // console.log(res)
      let forMatBoardArr = this.data.forMatBoardArr;
      res.forEach((v, index) => {
        forMatBoardArr.push(v.board_name)
      })
      this.setData({
        boardArr: res,
        forMatBoardArr: forMatBoardArr
      })
    }).catch(res => {
      console.log(res)
    })
    //请求定金信息
    http.getData("downpayment").then(res => {
      // console.log(res)
      let forMatDepositMoneyArr = this.data.forMatDepositMoneyArr;
      res.forEach((v, index) => {
        forMatDepositMoneyArr.push((parseInt(v.money) / 100 + '元'));
      })
      this.setData({
        depositMoneyArr: res,
        forMatDepositMoneyArr: forMatDepositMoneyArr
      })
    }).catch(res => {
      console.log(res)
    })
    this.setData({
      contactText: getApp().globalData.contactText,
      phoneText: getApp().globalData.phoneText,
    })

  },


  onShow() {
    this.setData({
      agreement: getApp().globalData.agreement
    })
  },
  //拒绝用户协议
  refused() {
    wx.navigateBack({
      delta: 1
    })
  },
  //同意用户协议
  agree() {
    wx.request({
      url: 'https://api.mokyun.com/pesticide/agree',
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'content-type': 'application/json',
        'APPID': 32
      },
      success: (res) => {
        getApp().globalData.agreement = false;
        this.setData({
          agreement: false
        })
      }
    })
  },



  //选择地址
  goLocation() {
    let that = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.userLocation']) {
          wx.authorize({
            scope: 'scope.userLocation',
            success(res) {
              wx.getLocation({
                type: "wgs84",
                success: function(res) {
                  wx.chooseLocation({
                    success: function(res) {
                      that.setData({
                        address: res.address
                      })
                    },
                  })
                },
              })
            },
            fail(res) {
              that.setData({
                isConfirm: false
              })
            }
          })
        } else {
          wx.getLocation({
            type: "wgs84",
            success: function(res) {
              wx.chooseLocation({
                success: function(res) {
                  that.setData({
                    address: res.address
                  })
                },
              })
            },
          })
        }
      }
    })
  },
  // 选择地址没有同意授权将打开用户设置
  goOpenLocation() {
    let that = this;
    wx.openSetting({
      success(res) {
        if (res.authSetting['scope.userLocation']) {
          that.setData({
            isConfirm: true
          })
        } else {
          console.log(222)
        }
      }
    })
  },

  //输入详细地址
  addressInput(e) {
    let that = this;
    that.setData({
      addressDetails: e.detail.value,
    })
  },

  //选择作业时间
  chooseTime() {
    let that = this;
    that.rili = that.selectComponent("#rili")
    let starTime = that.data.starTime;
    let endTime = that.data.endTime;
    let changeTime = this.data.time
    that.rili.xianShi({
      data: function(res) {
        if (res != null) {
          if (res.length == 0) {
            starTime = null
            endTime = null
            changeTime = true
          } else if (res.length == 1) {
            starTime = res[0].data;
            endTime = res[0].data;
            changeTime = false
          } else if (res.length == 2) {
            starTime = res[0].data
            endTime = res[1].data
            changeTime = false
          }
        } else {
          starTime = null
          endTime = null
          changeTime = true
        }
        that.setData({
          starTime: starTime,
          endTime: endTime,
          time: changeTime
        })
      }
    })
  },

  //作物类型选择
  cropChange(e) {
    // console.log(e)
    let index = e.detail.value;
    this.setData({
      cropTypeIndex: this.data.cropTypeArr[index].id,
      cropTypeText: this.data.cropTypeArr[index].crop_name
    })
  },

  //作业亩数选择
  areaInput(e) {
    // console.log(e)
    this.setData({
      areaDetails: e.detail.value
    })
  },

  //作业类型选择
  checkboxChange(e) {
    // console.log(e)
    let valueArr = e.detail.value;
    this.setData({
      valueArr: valueArr
    })
  },
  goNext() {
    let that = this;
    let changeNum = that.data.num;
    let address = that.data.address;
    let addressDetails = that.data.addressDetails;
    let starTime = that.data.starTime;
    let endTime = that.data.endTime;
    let cropTypeText = that.data.cropTypeText;
    let cropTypeIndex = that.data.cropTypeIndex; //作物类型id
    let areaDetails = that.data.areaDetails;
    let taskText = that.data.taskText;
    let valueArr = that.data.valueArr;
    let picUrl = that.data.picUrl;
    let contactText = that.data.contactText;
    let phoneText = that.data.phoneText;
    let pesText = that.data.pesText;
    let pesIndex = that.data.pesIndex;
    let boardText = that.data.boardText;
    let boardIndex = that.data.boardIndex;
    let isDepositShow = that.data.isDepositShow;
    let depositMoneyText = that.data.depositMoneyText;
    let moneyDetails = that.data.moneyDetails;
    let depositText = that.data.depositText;
    let depositMoneyIndex = that.data.depositMoneyIndex;
    let time = ' 00:00:00';
    let moneyReg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if (changeNum == 1) {
      if (address == '点击选择地址') {
        that.showToast('请选择地址')
      } else if (addressDetails == '') {
        that.showToast('请输入详细地址')
      } else if (starTime == null) {
        that.showToast('请选择作业时间')
      } else {
        that.setData({
          num: ++changeNum
        })
      }
    } else if (changeNum == 2) {
      if (cropTypeText == '点击选择类型') {
        that.showToast('请选择作物类型')
      } else if (areaDetails == '') {
        that.showToast('请输入作业亩数')
      } else if (taskText == '点击选择类型') {
        that.showToast('请选择作业类型')
      } else {
        that.setData({
          num: ++changeNum
        })
      }
    } else if (changeNum == 3) {
      if (contactText == '') {
        that.showToast('请填写联系人')
      } else if (phoneText == '') {
        that.showToast('请填写联系方式')
      } else if (pesText == '点击选择类型') {
        that.showToast('请选择农药类型')
      } else if (boardText == '点击选择类型') {
        that.showToast('请选择食宿类型')
      } else {
        that.setData({
          num: ++changeNum
        })
      }
    } else {
      // console.log(address)
      // console.log(addressDetails)
      // console.log(starTime + time)
      // console.log(endTime + time)
      // console.log(cropTypeIndex)
      // console.log(areaDetails)
      // console.log(valueArr)
      // console.log(valueArr.join(','))
      // console.log(picUrl)
      // console.log(picUrl.join(','))
      // console.log(contactText)
      // console.log(phoneText)
      // console.log(pesIndex)
      // console.log(boardIndex)
      // console.log(moneyDetails)
      // console.log(depositMoneyIndex)
      if (depositText == '是否支付定金') {
        that.showToast('是否支付定金')
      } else if (isDepositShow) {
        if (depositMoneyText == '点击选择金额') {
          that.showToast('请选择定金金额')
        } else if (moneyDetails == '') {
          that.showToast('请填写期望金额')
        } else if (!moneyReg.test(moneyDetails)) {
          that.showToast('请填写正确金额')
        } else {
          wx.request({
            url: 'https://api.mokyun.com/pesticide/create/order',
            method: 'POST',
            header: {
              'Accept': 'application/json',
              'Authorization': 'Bearer ' + wx.getStorageSync('token'),
              'content-type': 'application/json',
              'APPID': 32
            },
            data: {
              address: address, //地址
              address_detail: addressDetails, //详细地址
              start_time: starTime + time, // 开始时间
              end_time: endTime + time, // 结束时间
              crop_id: cropTypeIndex, // 作物类型id
              area: areaDetails, // 作业亩数
              task_id: valueArr.join(','), // 作业类型id
              pictures: picUrl.length == 0 ? '' : picUrl.join(','), // 图片
              linkman: contactText, // 联系人
              tel: phoneText, // 手机号码
              pesticide_id: pesIndex, // 农药类型
              board_id: boardIndex, // 食宿类型
              downpayment_id: depositMoneyIndex, // 定金
              expected_price: moneyDetails * 100, // 期望价格
            },
            success: (res => {
              that.setData({
                tradeNo: res.data
              })
              wx.request({
                url: 'https://api.mokyun.com/wechat/pay',
                method: 'POST',
                data: {
                  tradeNo: that.data.tradeNo
                },
                header: {
                  'Authorization': 'Bearer ' + wx.getStorageSync('token'),
                  'APPID': 32
                },
                success: function(res) {
                  wx.requestPayment({
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    signType: res.data.signType,
                    paySign: res.data.paySign,
                    success: function(res) {
                      wx.request({
                        url: "https://api.mokyun.com/pesticide/order/status",
                        method: 'POST',
                        data: {
                          tradeNo: that.data.tradeNo
                        },
                        header: {
                          'Authorization': 'Bearer ' + wx.getStorageSync('token'),
                          'APPID': 32
                        },
                        success: function(res) {
                          // console.log(res)
                          if (res.data == 'success') {
                            // wx.showToast({
                            //   title: '发布成功',
                            //   icon: 'none',
                            //   duration: 1500,
                            // })
                            // setTimeout(() => {
                            //   wx.reLaunch({
                            //     url: '/pages/index/index',
                            //   })
                            // }, 2500)
                            that.setData({
                              isSuccess: true
                            })
                          }
                        }
                      })
                    },
                    fail: function() {
                      wx.showToast({
                        title: '支付失败',
                        icon: 'none',
                        duration: 1500,
                        success: function() {
                          wx.redirectTo({
                            url: '/pages/order/order'
                          })
                        }
                      })
                    }
                  })
                }
              })
              // wx.showToast({
              //   title: '发布成功',
              // })
              // setTimeout(() => {
              //   wx.reLaunch({
              //     url: '/pages/index/index',
              //   })
              // }, 2000)

            })
          })
        }
      } else if (!isDepositShow) {
        if (moneyDetails == '') {
          that.showToast('请填写期望金额')
        } else if (!moneyReg.test(moneyDetails)) {
          that.showToast('请输入正确的金额')
        } else {
          wx.request({
            url: 'https://api.mokyun.com/pesticide/create/order',
            method: 'POST',
            header: {
              'Accept': 'application/json',
              'Authorization': 'Bearer ' + wx.getStorageSync('token'),
              'content-type': 'application/json',
              'APPID': 32
            },
            data: {
              address: address, //地址
              address_detail: addressDetails, //详细地址
              start_time: starTime + time, // 开始时间
              end_time: endTime + time, // 结束时间
              crop_id: cropTypeIndex, // 作物类型id
              area: areaDetails, // 作业亩数
              task_id: valueArr.join(','), // 作业类型id
              pictures: picUrl.length == 0 ? '' : picUrl.join(','), // 图片
              linkman: contactText, // 联系人
              tel: phoneText, // 手机号码
              pesticide_id: pesIndex, // 农药类型
              board_id: boardIndex, // 食宿类型
              downpayment_id: 0, // 定金
              expected_price: moneyDetails * 100, // 期望价格
            },
            success: (res => {
              // wx.showToast({
              //   title: '发布成功',
              // })
              // setTimeout(() => {
              that.setData({
                isSuccess: true
              })
              // }, 2000)
            })
          })
        }
      }
    }
  },
  goPrev() {
    let changeNum = this.data.num;
    this.setData({
      num: --changeNum
    })
  },
  //  农药选择
  pesChange(e) {
    // console.log(e.detail.value)
    let index = e.detail.value;
    this.setData({
      pesIndex: this.data.pesArr[index].id,
      pesText: this.data.pesArr[index].pesticide_name
    })
  },
  //  食宿选择
  boardChange(e) {
    // console.log(e.detail.value)
    let index = e.detail.value;
    this.setData({
      boardIndex: this.data.boardArr[index].id,
      boardText: this.data.boardArr[index].board_name
    })
  },


  //选择作业类型
  chooseTaskType() {
    this.setData({
      isShow: true
    })
  },

  choiceConfirm() {
    let boolArr = new Array(this.data.taskTypeArr.length)
    let arr = [];
    this.data.valueArr.forEach((item) => {
      this.data.taskTypeArr.forEach((val, index) => {
        if (item == val.id) {
          // console.log(index) //0  2
          arr.push(this.data.taskTypeArr[index].task_name)
          boolArr[index] = true
        }
      })
    });
    let data = '';
    arr.forEach(item => data += (' ' + item));
    this.setData({
      boolArr: boolArr,
      taskText: data,
      isShow: false
    })
  },
  choiceCancel() {
    this.setData({
      isShow: false
    })
  },


  //选择上传图片的函数
  chooseImage(e) {
    let that = this;
    wx.chooseImage({
      count: 9,
      success: function(res) {
        // console.log(res)
        let url = res.tempFilePaths,
          length = that.data.urls.length, //原urls数组的长度
          id = length - 1, //原urls数组的最大下标
          newAddPic = [],
          urlArr = [],
          currentId = e.currentTarget.dataset.id;
        //当数组长度小于9的时候,如果点击项的id===数组长度-1,也就是点击的是添加图片的按钮,那就添加图片
        //否则就更换点击项的图片
        //直到当图片达到9张后就不再添加图片,而是点击哪项就更换哪项的图片
        if (currentId === length - 1) {
          if (length === 9) {
            that.changePic(urlArr, that, that.data.urls, url[0], currentId);
            that.updateImg(url[0], that.data.uploadToken);
          } else {
            let len = length + url.length;
            if (len > 9) {
              url = url.slice(0, 9 - length + 1);
              // console.log(url.length)
            }
            that.addPic(that, url, id, length, urlArr, newAddPic);
            for (let i = 0; i < url.length; i++) {
              that.updateImg(url[i], that.data.uploadToken);
            }
          }
        } else {
          that.changePic(urlArr, that, that.data.urls, url[0], currentId);
          that.updateImg(url[0], that.data.uploadToken);
        };
      }
    })
  },
  //更换图片的函数
  changePic(urlArr, that, urls, url, currentId) {
    let picUrl = this.data.picUrl,
      strUrl = "";
    picUrl.splice(currentId, 1);
    this.setData({
      picUrl: picUrl
    })
    urlArr = urls;
    urlArr[currentId] = {
      url,
      id: currentId
    };
    that.setData({
      urls: urlArr
    });
  },

  //添加图片的函数
  addPic(that, url, id, length, urlArr, newAddPic) {
    let arr = [];
    for (var i = 0; i < length - 1; i++) {
      urlArr.push({
        url: that.data.urls[i].url,
        id: that.data.urls[i].id
      });
    }
    for (var i = 0; i < url.length; i++) {
      urlArr.push({
        url: url[i],
        id: length + i - 1
      });
    }
    if (urlArr.length > 9) {
      arr = urlArr.slice(0, 9)
      let picUrl = that.data.picUrl;
      picUrl = picUrl.slice(0, 9);
      that.setData({
        picUrl: picUrl
      })
    } else if (urlArr.length == 9) {
      arr = urlArr;
    } else {
      arr = urlArr;
      arr.push({
        url: that.data.addPicUrl,
        id: arr.length
      });
    }
    that.setData({
      urls: arr
    });
  },

  //上传图片到七牛云
  updateImg: function(filePath, uptoken) {
    var that = this
    qiniuUploader.upload(filePath, (res) => {
      that.data.picUrl.push(res.imageURL);
    }, (error) => {
      console.log('error: ' + error);
    }, {
      // key: pciName,
      region: 'ECN',
      uptoken: uptoken,
      uploadURL: 'https://up.qbox.me',
    });

  },

  //联系人输入
  contactInput(e) {
    // console.log(e)
    this.setData({
      contactText: e.detail.value
    })
  },
  //联系方式输入
  phoneInput(e) {
    // console.log(e)
    this.setData({
      phoneText: e.detail.value
    })
  },
  //是否支付定金
  depositChange(e) {
    // console.log(e)
    let index = e.detail.value;
    if (index == 0) {
      this.setData({
        depositIndex: index,
        isDepositShow: true,
        depositText: this.data.depositArr[index]
      })
    } else {
      this.setData({
        isDepositShow: false,
        depositIndex: index,
        depositText: this.data.depositArr[index]
      })
    }
  },
  //定金金额选择
  depositMoneyChange(e) {
    let index = e.detail.value;
    this.setData({
      depositMoneyIndex: this.data.depositMoneyArr[index].id,
      depositMoneyText: parseInt(this.data.depositMoneyArr[index].money) / 100 + '元'
    })
    // console.log(this.data.depositMoneyIndex)
  },
  //期望金额填写
  moneyInput(e) {
    // console.log(e)
    this.setData({
      moneyDetails: e.detail.value
    })
  },
  showToast(title) {
    wx.showToast({
      title: title,
      icon: 'none',
      image: '/images/tanhao.png'
    })
  },
  goOrder() {
    wx.redirectTo({
      url: '/pages/order/order',
    })
  }
})